// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.

// this is regression test for VSWhidbey 549411
// The exception was not correctly caught, and so cleanup did not happen in the right way.
// we make sure exception is caught exactly once

using System;

public interface I
{
    void Foo();
}

public class X : I
{
    public void Foo()
    {
    }
}

public class Y : I
{
    public void Foo()
    {
    }
}

public class TrustedClass
{
	public static int DoWork(I[] arrI)
    	{
    		int counter = 0;
		 
        	try
        	{
            		foreach (I i in arrI)
            		{
                		i.Foo();
            		}
        	}
        	catch (NullReferenceException)
        	{
        		counter++;
        	}

		return counter;
    }
}


public class Exploit
{
	private static int NUM_ELEM = 1000;
	
    	public static int DoExploit()
    	{
        
		 I[] arrI = new I[NUM_ELEM];
		
        	for (int i = 0; i < NUM_ELEM; i++)
        	{
            		if (i % 2 == 0)
            		{
                		arrI[i] = new X();
            		}
            		else
            		{
                		arrI[i] = new Y();
            		}
        	}
        	arrI[NUM_ELEM-1] = null;

        	return TrustedClass.DoWork(arrI);
    	}
}

public class CMain
{
	public static int Main()
    	{
    		// we should get into the catch block of DoWork() one time
		if ( Exploit.DoExploit()  == 1)
		{
			Console.WriteLine("PASS");
			return 100;
		}
		else
		{
			Console.WriteLine("FAIL");
			return 101;
		}
    	}
}
